<template>
    <div @contextmenu.prevent="handleRightClick" class="file-item" :class="{ active: store.currentFile == fileRecord2 }"
        @click="openFileForPath(fileRecord2)">
        <img class="file-item-img" src="../../assets/doc_blue.png" alt="">
        <span>{{ fileRecord2 }}</span>
    </div>
    <RightClickMenu :is-open="isOpen" :pos="pos" :file-record="fileRecord2" @menuClick="handleMenuClick">
    </RightClickMenu>
</template>

<script setup>
import { useStore } from '../../store/store'
import RightClickMenu from './RightClickMenu.vue'
import { ref } from 'vue'
import { invoke } from '@tauri-apps/api/core'
import { inject } from 'vue'

const toast = inject('toast')
const dialog = inject("dialog")
const inputDialog = inject("inputDialog")
const store = useStore()
const isOpen = ref(false)
const pos = ref({ x: 0, y: 0 })


//对于传递给子组件的props都是只读的，如果要修改需要emit向父组件通信
const props = defineProps(['fileRecord', 'currentFileRecord'])
const fileRecord2 = ref(props.fileRecord)

function openFileForPath(filePath) {
    store.currentFile = filePath
}

function handleRightClick(event) {
    //先检查当前是否有打开的currMenu
    if (store.currentMenu) {
        return;
    }
    console.log("handleRightClick", event.clientX, event.clientY);
    //显示弹窗，获取点击的坐标，实现从x,y处开始加载菜单
    pos.value = { x: event.clientX, y: event.clientY }
    isOpen.value = true
    store.currentMenu = true
}

const handleMenuClick = async ({ action, record }) => {
    console.log('handleMenuClick:', action, record)
    store.currentMenu = false
    isOpen.value = false
    switch (action) {
        case 'remove':
            const dialogRemoveFlag = await dialog(" 移除警告", "是否确定移除记录，此操作不会删除文件~~~")
            console.log("dialogRemoveFlag:", dialogRemoveFlag)
            if (dialogRemoveFlag) {
                // 移除记录，从fileList当中移除
                const index = store.fileList.indexOf(record)
                if (index > -1) {
                    store.fileList.splice(index, 1)
                }
                // 先判断需要移除的文件是不是currentFile，是的话就置为数组第一个，当为空的时候，就设置为'''
                if (record == store.currentFile) {
                    if (store.fileList.length == 0) {
                        console.log('fileList为空')
                        store.currentFile = '';
                    } else {
                        store.currentFile = store.fileList[0]
                    }
                }
                toast("移除成功~~~", "success")
            } else {
                // toast("操作已取消", "info")
            }
            break
        case 'delete':
            //进行弹窗
            const dialogDeleteFlag = await dialog(" 删除警告", "是否确定删除记录，此操作会删除文件!!!")
            console.log("dialogDeleteFlag:", dialogDeleteFlag)
            if (dialogDeleteFlag) {
                let deleteFlag = deleteFile(record)
                if (deleteFlag) {
                    //删除成功
                    // 移除记录，从fileList当中移除
                    const index = store.fileList.indexOf(record)
                    if (index > -1) {
                        store.fileList.splice(index, 1)
                    }
                    // 先判断需要移除的文件是不是currentFile，是的话就置为数组第一个，当为空的时候，就设置为'''
                    if (record == store.currentFile) {
                        if (store.fileList.length == 0) {
                            console.log('fileList为空')
                            store.currentFile = '';
                        } else {
                            store.currentFile = store.fileList[0]
                        }

                    }
                    toast("删除成功~~~", "success")
                } else {
                    //删除失败,则进行提示
                    toast("删除失败,可能没有权限以及文件不存在!!!", "error")
                }
            } else {
                // toast("操作已取消", "info")
            }
            break
        case 'rename':
            //判断文件是否存在，略
            const records = record.split('\\')
            const recordName = records[records.length - 1].split('.')[0]
            const simpleName = await inputDialog("重命名提示", recordName.split('.')[0])
            // 获取输入名字，record文件，以及要更新的名字
            // console.log('====1',recordName);
            // console.log('====2',simpleName);
            // if(recordName === simpleName){
            //     toast("名字相同", "info")
            //     break
            // }
            rename(record, simpleName)
            break
        case 'close':
            // 关闭逻辑
            store.currentMenu = false
            isOpen.value = false
            // toast("操作成功", "success")
            break
    }
}

const rename = async (oldPath, simpleName) => {

    if (simpleName === '') {
        // toast("操作已取消", "info")
        return
    }

    //对名字进行拼接修改
    const oldPathArr = oldPath.split('\\')
    console.log('oldPathArr', oldPathArr)
    //判断是否有后缀
    let indexRes = simpleName.indexOf(".txt")
    console.log(indexRes)
    if (indexRes == -1) {
        //添加后缀
        console.log("添加后缀")
        simpleName = simpleName + ".txt"
        console.log(simpleName)
    }

    //判断名字是否相同
    if (oldPathArr[oldPathArr.length - 1] === simpleName) {
        //名字相同则不需要改
        toast("名字相同~~~", "info")
        return
    }

    oldPathArr[oldPathArr.length - 1] = simpleName
    console.log('newPathArr', oldPathArr)

    //判断名字是否非法
    if (simpleName.indexOf("..") !== -1
        || simpleName.indexOf('/') !== -1
        || simpleName.indexOf('\\') !== -1
        || simpleName.indexOf(':') !== -1
        || simpleName.indexOf('*') !== -1
        || simpleName.indexOf('?') !== -1
        || simpleName.indexOf('"') !== -1
        || simpleName.indexOf('<') !== -1
        || simpleName.indexOf('>') !== -1
        || simpleName.indexOf('|') !== -1) {
        console.log('名字包含非法字符')
        toast('包含非法字符', "error")
        return

    }


    try {
        const newPath = oldPathArr.join('\\')
        console.log('newPath', newPath)
        const res = await invoke('rename_file', {
            oldPath: oldPath,
            newPath: newPath
        });
        console.log(res);

        console.log('重命名成功');
        toast("重命名成功~~~", "success")

        //修正
        fileRecord2.value = newPath
        for (let i = 0; i < store.fileList.length; i++) {
            console.log('fileList==>', store.fileList[i]);
            if (store.fileList[i] === oldPath) {
                store.fileList[i] = newPath
            }
        }
        return true
    } catch (error) {
        console.error('重命名错误:', error);
        toast('重命名错误:' + error, "error")
        return false
    }
}

const deleteFile = async (path) => {
    try {
        await invoke('delete_file', { path })
        console.log('删除成功')
        return true
    } catch (e) {
        console.error('删除失败:', e)
        return false
    }
}

</script>

<style lang="scss" scoped>
.file-item {
    display: flex;
    align-items: center;
    padding: 6px 15px;
    border-radius: 4px;
    margin: 2px 8px;
    cursor: pointer;
    transition: all 0.2s;
    font-size: 13px;
}


.file-item-img {
    height: 15px;
    height: 15px;
    border-radius: 5px;
    border-radius: 5px;
    margin-right: 5px;
}

.file-item:hover {
    background-color: #3a4f8fff;
}

.file-item.active {
    background-color: #656c81;
    color: #fff;
}
</style>